package com.juma.cartridge.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/23 10:48
 * @Description: Hessian实现序列化、反序列化
 */
public class HessianIOUtils {
 
    /**
     * Hessian实现序列化
     * @param employee
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = null;
        HessianOutput hessianOutput = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            hessianOutput = new HessianOutput(byteArrayOutputStream);
            hessianOutput.writeObject(obj);
            return byteArrayOutputStream.toByteArray();
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {}
            
            try {
                hessianOutput.close();
            } catch (IOException e) {}
        }
    }
 
    /**
     * Hessian实现反序列化
     * @param employeeArray
     * @return
     */
    public static <T> T deserialize(byte[] array) throws IOException {
        ByteArrayInputStream byteArrayInputStream = null;
        HessianInput hessianInput = null;
        try {
            byteArrayInputStream = new ByteArrayInputStream(array);
            hessianInput = new HessianInput(byteArrayInputStream);
            return (T)hessianInput.readObject();
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {}
            try {
                hessianInput.close();
            } catch (Exception e) {}
        }
    }
    
}
